package com.superhelper.app.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.superhelper.app.common.CommonHelper;
import com.superhelper.app.domain.Admin;
import com.superhelper.app.domain.InvitationCode;
import com.superhelper.app.mapper.AdminMapper;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.LoginLog;
import com.superhelper.common.service.RedisService;
import com.superhelper.common.utils.CryptUtil;

@Service
public class AdminService {
    @Autowired(required = true)
    private AdminMapper adminMapper;
    @Autowired(required = true)
    private RedisService redisService;

    public Admin getAdminById(Long userId) {
        Admin user = adminMapper.getAdminById(userId);
        if (user != null) {
            InvitationCode invitCode = adminMapper.getInvitationCodeByUserId(user.getId());
            user.setInvitCode(invitCode);
        }
        return user;
    }

    public Admin getAdminByUsername(String username) {
        Admin user = adminMapper.getAdminByUsername(username);
        if (user != null) {
            InvitationCode invitCode = adminMapper.getInvitationCodeByUserId(user.getId());
            user.setInvitCode(invitCode);
        }
        return user;
    }

    public int addLoginLog(LoginLog ll) {
        adminMapper.updateLoginAt(ll.getUserId(), ll.getLoginTime());
        return adminMapper.addLoginLog(ll);
    }

    public int updatePackageName(String packageName, String plfFrom, Long auserId) {
        return adminMapper.updatePackageName(packageName, plfFrom, auserId);
    }

    public int createUser(Admin user) {
        user.setImid(CryptUtil.md5(user.getUsername()));
        int res = adminMapper.addUser(user);
        if (res > 0) {
            Integer roleId = 6;// 默认角色
            adminMapper.addUserRole(user.getId().intValue(), roleId);
            String inviteCode = this.createCode("register", 7); // 7天试用期
            this.updateUserCode(user.getId(), inviteCode);
        }
        return res;
    }

    public int updatePwd(String phone, String pwd) {
        return adminMapper.updatePwd(phone, pwd);
    }

    public void setUserOnline(Long userId) {
        String online_key = String.format(com.superhelper.common.Consts.Redis.USER_ONLINE, userId);
        Admin admin = redisService.get(online_key, Admin.class);
        if (admin == null) {
            admin = this.getAdminById(userId);
        }
        redisService.set(online_key, 600, admin);// 10分钟不没有访问，表示离线
    }

    public List<AuserShop> getAuserShopsByAuserId(Long userId) {
        return adminMapper.getAuserShopsByAuserId(userId);
    }

    public InvitationCode getInvitationCode(String code) {
        return adminMapper.getInvitationCodeByCode(code);
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public int updateUserCode(Long userId, String inviteCode) {
        InvitationCode code = adminMapper.getInvitationCodeByCode(inviteCode);
        Calendar c = Calendar.getInstance();
        if (code.getExpireType() == 7) {
            c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + code.getExpireType());
        } else {
            Admin admin = adminMapper.getAdminById(userId);
            long time = System.currentTimeMillis();
            if (admin.getExpireAt().getTime() < time) {
                c.setTime(new Date());
            } else {
                c.setTime(admin.getExpireAt());
            }
            c.set(Calendar.MONTH, c.get(Calendar.MONTH) + code.getExpireType());
        }
        int res = adminMapper.updateCode(userId, code.getCode());
        if (res > 0) {
            adminMapper.updateUserExpireAt(userId, c.getTime());
        }
        return res;
    }

    public String createCode(String plfFrom, int expireType) {
        int i = 0;
        do {
            String code = CommonHelper.createCode();
            InvitationCode codeEntity = new InvitationCode();
            codeEntity.setPlfFrom(plfFrom);
            codeEntity.setExpireType(expireType);
            codeEntity.setCode(code);
            int res = adminMapper.addCode(codeEntity);
            if (res > 0) {
                return code;
            }
            i++;
        } while (i < 5);
        return null;
    }
}
